package com.shsxt.service;



import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.LogFactory;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.jdom.JDOMException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.shsxt.controller.YunTongXun;
import com.shsxt.dao.ControllDao;
import com.shsxt.dao.CouponDao;
import com.shsxt.dao.OrderDao;
import com.shsxt.dao.WodeDao;
import com.shsxt.dao.YuyueDao;
import com.shsxt.model.Activity;
import com.shsxt.model.COrder;
import com.shsxt.model.CheckNumber;
import com.shsxt.model.Coupon;
import com.shsxt.model.DOrder;
import com.shsxt.model.JOrder;
import com.shsxt.model.KOrder;
import com.shsxt.model.Location;
import com.shsxt.model.Lunbo;
import com.shsxt.model.ROrder;
import com.shsxt.model.SOrder;
import com.shsxt.model.Unifiedorder;
import com.shsxt.model.UserInfo;
import com.shsxt.model.Version;
import com.shsxt.model.WCPayGetPrePayIdRespInfo;
import com.shsxt.util.Yuiyn;
import com.shsxt.util.weixin.PayCommonUtil;
import com.shsxt.util.weixin.WCPayUtils;
import com.shsxt.util.weixin.XMLUtil;
import com.shsxt.util.wx.ConfigUtil;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;
import ytx.org.apache.http.HttpEntity;
import ytx.org.apache.http.HttpResponse;

@Service
public class ControllService {
	@Autowired
	private YuyueService yuyueService;
	@Autowired
	private ControllDao controllDao;
	@Autowired
	private CouponDao couponDao;
	@Autowired
	private OrderDao orderDao;
	@Autowired
	private YuyueDao yuyueDao;
	@Autowired
	private WodeDao wodeDao;
	@Autowired
	private WodeService wodeService;
	public Map<String, Object> cdkey(String count) {
		Map<String,Object> map=new HashMap<String,Object>();
		Map<String,Object> param=new HashMap<String,Object>();
		param.put("count", count);
		String uuid="";
		for(int i=0;i<10;i++){
			uuid=UUID.randomUUID().toString().substring(0, 8);
			param.put("uuid", uuid);
			controllDao.createUUID(param);
		}
		map.put("0", "成功生成10条兑换码");
		return map;
	}

	public Map<String, Object> create_yueman() throws ParseException {
		Map<String,Object> map=new HashMap<String,Object>();
		Map<String,Object> param=new HashMap<String,Object>();
		String startdate="2017-04-12";
		for(int i=0;i<1000;i++){
			Date date = (new SimpleDateFormat("yyyy-MM-dd")).parse(startdate);
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			cal.add(Calendar.DATE,1);
			date =cal.getTime();
			startdate = (new SimpleDateFormat("yyyy-MM-dd")).format(date);//加一天后结果
			param.put("time", startdate);
			for(int x=0;x<10;x++){
				if(x==0){
					param.put("type", "日常保洁");
					controllDao.createYueman(param);	
				}else if(x==1){
					param.put("type", "沙发护理");
					controllDao.createYueman(param);	
				}else if(x==2){
					param.put("type", "地板护理");
					controllDao.createYueman(param);	
				}else if(x==3){
					param.put("type", "开荒保洁");
					controllDao.createYueman(param);	
				}else if(x==4){
					param.put("type", "擦玻璃");
					controllDao.createYueman(param);	
				}else if(x==5){
					param.put("type", "冰箱");
					controllDao.createYueman(param);	
				}else if(x==6){
					param.put("type", "空调");
					controllDao.createYueman(param);	
				}else if(x==7){
					param.put("type", "洗衣机");
					controllDao.createYueman(param);	
				}else if(x==8){
					param.put("type", "油烟机");
					controllDao.createYueman(param);	
				}
			}
		}
		
		map.put("0", "成功");
		return map;
	}

	public Map<String, Object> weixin(String openid ) {
		Map<String,Object> param=new HashMap<String,Object>();
		Map<String,Object> map=new HashMap<String,Object>();
		param.put("openid", openid);
		String newToken= UUID.randomUUID().toString();
		UserInfo user=controllDao.findWeixin(param);
		if(user==null){
			map.put("phoneNumber", "未绑定");
			map.put("token", "未绑定");
			map.put("token", "");
			return map;
		}else{
			map.put("phoneNumber", user.getPhoneNumber());
			map.put("token", newToken);
			param.put("phoneNumber", user.getPhoneNumber());

			param.put("token", newToken);
			controllDao.updateToken(param);
			return map;
		}
		
		
		
	}

	public Map<String, Object> weixinbinding(String type,String number,String phoneNumber,String openid,String head,String name,String sex ) throws ParseException, APIConnectionException, APIRequestException {
		Map<String,Object> map=new HashMap<String,Object>();
		Map<String,Object> duanxin=wodeService.duanxin(phoneNumber,type,number);
		//绑定微信 验证码失败
		if(!duanxin.get("0").equals("成功")){
			map.put("0", duanxin.get("0"));
			return map;
		}
		UserInfo user=wodeDao.findUserByPhone( phoneNumber);
		Map<String,Object> param=new HashMap<String,Object>();
		

		param.put("phoneNumber", phoneNumber);
		param.put("openid", openid);
		param.put("head", head);
		param.put("name", name);
		param.put("sex", sex);
		param.put("fullPath", head);
		//创建纯微信账号
		if(user==null){
			controllDao.createWeixin(param);
			wodeService.registerCoupon(phoneNumber);
		}else{
			//已有手机账号 添加微信号
			controllDao.updateOpenid(param);
			if("".equals(user.getHeadPortrait())||user.getHeadPortrait()==null){
				wodeDao.updateHeadStr(param);
			}
		}
		String newToken= UUID.randomUUID().toString();
		map.put("0", newToken);
		param.put("token", newToken);
		controllDao.updateToken(param);
		return map;
	}

	public Map<String, Object> token(String phoneNumber, String token) throws ParseException {
		Map<String,Object> map=new HashMap<String,Object>();
		 if(phoneNumber!=null&&!phoneNumber.equals("")){
	       	 UserInfo user= wodeDao.findUserByPhone(phoneNumber);
	       	 //token错误
	       	 if(!user.getToken().equals(token)){
	       		 map.put("0", "TOKEN错误");
	       		 	return map;
	       		 	//5天为访问 token过期
	       	 }else if(user.getToken().equals(token)&&(new Date().getTime()-new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(user.getTime()).getTime())>60*60*24*5*1000){
	       		 map.put("0", "TOKEN错误");
	       		 	return map;
		     }else{
		       		 wodeDao.updateTimeByPhone(phoneNumber);
		       		 map.put("0", "TOKEN正确");
		       		 	return map;
		     }
	        }else{
	        	 map.put("0", "TOKEN错误");
	       		 	return map;
	        }
	    
	}

	public Map<String, Object> lunbo() {
		List<Lunbo> lb=controllDao.findLunbo();
		Map<String,Object> map=new HashMap<String,Object>();
		
		map.put("A", lb);
		return map;
	}

	public Map<String, Object> buyVip(String vip ,String phoneNumber) throws ParseException {
		//实例化客户端
		Map<String,Object> map=new HashMap<String,Object>(); 
		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","2017041706761280", "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC6gPcD83dvy5w4JqudeYD1PiT0UdnMNQcoTiaLoIJPMwPwtngB7ov6iFdxRUoADVAjJfijGj8R3qlZX5/5KqQZM2VGMmN5Nt5G9zaX2D0m1MXewjJfRakgGF1Z5WMCs6YZp464YR9JgnmA+XzRroFu83EWHs59mGfjHMNcYhx27k6CaE3PkMk3IOjuFUw9AJDncGjRwxFQkC5HLjz78J5fETFbb6OtRiiWlC6QsvR8Kl7s3RMn/otSuyTfgQDIITDgNFV6skksrKJqUlj5p5JxHCGgkldCoSrME/0/QiKTO1hRtMflrxwnlQqtxyblwck34asjx1+9gatz3//HVxpnAgMBAAECggEAMzIPnJAKqy+TNH65AUNHOQrUDhUh2kJ8Mn4xaoam/qKcZElSbAVVe3JNvpQsmhMNeniD5hHgWkFq71OmkDk6ToijNj/CupVrMsPNwqTjNHOX1Wwtc6WlpV/K0FB9e1JhOA2cydQvSHh+bf8OWmiyswg0dMQEHsnlSpysrAFqmuKa1jqNYYhJuUx6VZOFgmPKVQCd3VIA9JTP3KL73n7uJIjJZI+1OtbW2I2/w22kYrWDCT0GdizaYqPWNRetpBB/81a8VAIJiRpmCKcPcPsudURvhEx6Fg9jzYfQqNU31ZhTRPY+Ad4f4gNsRq2INKMwgPo6Q2MwYReUW69/Q2QI0QKBgQD3tWAu9hKprlMbOs2mr4knn/c++BDxp47iHoQybnH7cABLAIIVvJamz8CItyBiydSP7afa3ZSwzGA5ScjhetePCH2IU1lRY5V2UisC4o/tidqD1JBuW7sVvYejDv0M00p9CSsuWoLnXqtx2PZQInEgcf+qqc+c271X0Q7grOVGXQKBgQDAvx+TyqQg0ivtQxAphimBWGTGCokUftSNOhHir/Lb6z02pp3XGoy0W/M0rNdqyVUhEMui+JmaGRfTzqt5uUrTyuz3SvI0VSw+v9NvIne0m2Wiy6M3jvbKVedO/pR6xai52koXVh7yf7j7lkNLInAXc9mWo2KiAZ1QxaA2mU1PkwKBgAqSXhmC/Qbq3rchylcb1MGxLQ8t7SMzIID8Bm5Ukl7Fx+1rhyHAW7mg0jnDfwlYTc8auHg5zrfA8TZgtMcSxBJhrWHdFMnJcz6KgTVtT/E2WfIYZ1Weapyh6yEFab1bYyl087fVuxJ+0thYByMiZSuaUewJtUefhTQzQuxJ1LstAoGBAJc+IWgVzT4XzPIq+maq6KyfEMw5fiD/+Ics9tXa3IVmjCzzBs2//oKT2D4QFiSsAMmmZTPnQJgjcof4FqO4GpggFlthirY30zUVzrHY6PdmLJVWlydEXjCcwZlBuH6x1NipChRPto7wW9XGrd0qE6zDcgx6/i1DeQ7lU/cjyf9TAoGBAIfEDIItVLQPLmofl8hmoGKmXLTXcU3s402737T+9C32ULAlwjKOPk+FnHMvV7Rn5l3ObZAuClpeYYSZB0KF+T6+FhjDMhjdQHpE1av/tK1p6SVBXdjHSTae01vKd76Hadqi7adqmYqiTZ5sCBeitoTO0deiuPUU1MvD6P9pn8oM","json","utf-8","MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgUzgScmclb96eh8AWc6TOOFK1dC2g2E4/S+q0WYQ3e633nkG7uxy0j1V+j/2PKLTn3XEMxWENBHkgrNmnmelYdzhonvt89pAo5Np3Fwma7lAtQOXdmAcQFwio6hU2kruPxJ0Zc+y/0uZzOC33QMNQP7tXUA+n8c/hCU9uoXzLGh5wl/84gKukwlK/BQ7FTNFb+KV/LnN2Z/Xvzux1E+rD8FhGhIHwSMCUaD4lkB0WCol/vFy3FNdnooo7xoFD+z0RhHID3lQIQdTfNbHQtSYw+t7F1J+nTDDq94nvWaG5d0u1Lqr9m2jCFihoOsKS3q9lcnmyU2QkC0bY1XfMf3AGQIDAQAB", "RSA2");
		//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
		AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
		//SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
		AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
		Map<String,Object> param=new HashMap<String,Object>(); 
		String uuid=UUID.randomUUID().toString();
		
		param.put("number",uuid );
		param.put("phoneNumber", phoneNumber);
		param.put("vip", vip);
		controllDao.createVip(param);
		String price="";
		if(vip.equals("1")){
			price="200";
		}else if(vip.equals("2")){
			price="500";
		}else if(vip.equals("3")){
			price="1000";
		}else if(vip.equals("4")){
			price="3000";
		}else if(vip.equals("5")){
			price="5000";
		}else if(vip.equals("6")){
			price="2999";
		}else if(vip.equals("7")){
			price="4999";
		}else if(vip.equals("8")){
			price="9999";
		}
		model.setBody(vip+"我是云家洁");
		model.setSubject(phoneNumber);
		model.setOutTradeNo(uuid);
		model.setTimeoutExpress("30m");
		model.setTotalAmount("0.01");
/*		model.setTotalAmount(price);
*/		model.setProductCode("QUICK_MSECURITY_PAY");
		request.setBizModel(model);
		request.setNotifyUrl("http://139.196.102.135/cleaning/controll/yzbuyVip");
		try {
		        //这里和普通的接口调用不同，使用的是sdkExecute
		        AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
		        map.put("0", response.getBody());
		        return map;//就是orderString 可以直接给客户端请求，无需再做处理。
		    } catch (AlipayApiException e) {
		        e.printStackTrace();
		}		return null;
	}
	public String yzbuyVip() throws AlipayApiException, ParseException {
		//获取支付宝POST过来反馈信息
		Map<String,Object> map=new HashMap<String,Object>(); 
		Map<String,Object> param=new HashMap<String,Object>(); 
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();  
		Map<String,String> params = new HashMap<String,String>();
		Map<String, String[]> requestParams = request.getParameterMap();
		String uuid="";
		String phoneNumber="";
		String count="";
		String vip="";
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
		    String name = (String) iter.next();
		    String[] values = (String[]) requestParams.get(name);
		    String valueStr = "";
		    for (int i = 0; i < values.length; i++) {
		        valueStr = (i == values.length - 1) ? valueStr + values[i]
		                    : valueStr + values[i] + ",";
		       if(name.equals("out_trade_no")){
		    	   uuid=values[i];
		       }else if(name.equals("subject")){
		    	   phoneNumber=values[i];
		       }else if(name.equals("price")){
		    	   count=values[i];
		       }else if(name.equals("body")){
		    	   vip=values[i].substring(0, 1);
		       }
		    }
		    params.put(name, valueStr);		 
		}
		//切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
		//boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
		boolean flag = AlipaySignature.rsaCheckV1(params, "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgUzgScmclb96eh8AWc6TOOFK1dC2g2E4/S+q0WYQ3e633nkG7uxy0j1V+j/2PKLTn3XEMxWENBHkgrNmnmelYdzhonvt89pAo5Np3Fwma7lAtQOXdmAcQFwio6hU2kruPxJ0Zc+y/0uZzOC33QMNQP7tXUA+n8c/hCU9uoXzLGh5wl/84gKukwlK/BQ7FTNFb+KV/LnN2Z/Xvzux1E+rD8FhGhIHwSMCUaD4lkB0WCol/vFy3FNdnooo7xoFD+z0RhHID3lQIQdTfNbHQtSYw+t7F1J+nTDDq94nvWaG5d0u1Lqr9m2jCFihoOsKS3q9lcnmyU2QkC0bY1XfMf3AGQIDAQAB", "utf-8", "RSA2")	;
		if(flag==true){
			param.put("type", "购买会员卡");
			param.put("message", "用户:"+phoneNumber);
			param.put("count", "+"+count);
			toVip(vip,phoneNumber);
			controllDao.createTongji(param);
			controllDao.updateVip(uuid);
		}
		return "success";
	
	}
	//购买会员卡支付的逻辑
	public Map<String, Object> toVip(String vip,String phoneNumber) throws ParseException {
		Map<String, Object> map = new HashMap<String,Object>();
		Map<String, Object> param = new HashMap<String,Object>();
		UserInfo user=wodeDao.findUserByPhone(phoneNumber);
		//用户的年卡到期大于现在的时间
		Boolean a=(new SimpleDateFormat("yyyy-MM-dd").parse(user.getNianka())).getTime()>=new Date().getTime();
	
		param.put("phoneNumber", phoneNumber);
			//判断购买的会员卡是否能提升会员等级
		if((Integer.valueOf(		wodeDao.findUserByPhone(phoneNumber).getMemberLevel().substring(3, 4)
				)<Integer.valueOf(vip))){
			param.put("vip", "VIP"+vip);

		}else{
			param.put("vip",wodeDao.findUserByPhone(phoneNumber).getMemberLevel());
		}
		//增加用户对应卡的余额
		if(vip.equals("1")){
			param.put("memberBalance",200 );
			couponDao.toVip(param);
		}else if(vip.equals("2")){
			param.put("memberBalance",500 );
			couponDao.toVip(param);
		}else if(vip.equals("3")){
			param.put("memberBalance",1000 );
			couponDao.toVip(param);
		}else if(vip.equals("4")){
			param.put("memberBalance",3000 );
			couponDao.toVip(param);
		}else if(vip.equals("5")){
			param.put("memberBalance",5000 );
			couponDao.toVip(param);
		}else if(vip.equals("6")){
			
			if(a){
				param.put("year",addDay(new SimpleDateFormat("yyyy-MM-dd").parse(user.getNianka()),1));
			}else{
				param.put("year",addDay(new Date(),1) );
			}
			controllDao.toNianka(param);
		}else if(vip.equals("7")){
			if(a){
				param.put("year",addDay(new SimpleDateFormat("yyyy-MM-dd").parse(user.getNianka()),2));
			}else{
				param.put("year",addDay(new Date(),2) );
			}
			controllDao.toNianka(param);
		}else if(vip.equals("8")){
			if(a){
				param.put("year",addDay(new SimpleDateFormat("yyyy-MM-dd").parse(user.getNianka()),3));
			}else{
				param.put("year",addDay(new Date(),5) );
			}
			controllDao.toNianka(param);
		}
		map.put("0", "成功");
		return map;
	}

	public static void push(String appKey,String materSecret,String message) throws APIConnectionException, APIRequestException{
		JPushClient jPushCilent=new JPushClient(materSecret,appKey);
		PushPayload payload=PushPayload.newBuilder()
				.setPlatform(Platform.all())
				.setAudience(Audience.all())
				.setNotification(Notification.alert(message))
				.setMessage(Message.content(message))
				.build();
		PushResult result=jPushCilent.sendPush(payload);
	
	}
	public static void pushOne(String appKey,String materSecret,String message,String phoneNumber) throws APIConnectionException, APIRequestException{
		/*String materSecret="1dd0e3924e7394137bc20d57";
		String appKey="8f6965a441a0aa10011c7063";*/
		//阿姨
		/*String materSecret="b2588d7dcaa473f3975c86fc";
		String appKey="587fc17e9c0cc048c2a3e10a";*/
		JPushClient jPushCilent=new JPushClient(materSecret,appKey);
		PushPayload payload=PushPayload.newBuilder()
				 .setPlatform(Platform.all())
	                .setAudience(Audience.alias(phoneNumber))/*15356506227,13843838438*/
	                .setNotification(Notification.alert(message))
	                .build();
		PushResult result=jPushCilent.sendPush(payload);
		/*PushPayload payload=PushPayload.alertAll("我输出了"); 
		PushResult result=jPushCilent.sendPush(payload);
		System.err.println("s:="+result);*/
	}

	public Map<String, Object> send(String phoneNumber) {
 Yuiyn.test1(phoneNumber);
return null;
	}

	public void lunboup(HttpSession session,HttpServletRequest request,
				HttpServletResponse response) throws IllegalStateException, IOException, ParseException {
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
						request.getSession().getServletContext());
				if (multipartResolver.isMultipart(request)) {
					MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
					//获取所有文件
					Iterator<String> iter = multiRequest.getFileNames();
					while (iter.hasNext()) {
						//获取当前文件
						MultipartFile file = multiRequest.getFile((String) iter.next());
						String fileName = file.getOriginalFilename();//储存地址
						if(fileName.substring(fileName.length()-4, fileName.length()).equals("peg")){
							fileName="lb"+System.currentTimeMillis()+fileName.substring(fileName.length()-5, fileName.length());
						}else{
							fileName="lb"+System.currentTimeMillis()+fileName.substring(fileName.length()-4, fileName.length());

						}
						if (fileName != null&&!fileName.equals("")) {//文件内容不为空
							//自动获取的是root/images里的图片
							String path1 = session.getServletContext().getRealPath("/images")+File.separator;// 储存地址+文件名 
							String path = path1 +fileName;//创建文件
							//leaning/images里的图片地址
							String path2="C:\\Program Files\\Tomcat 7.0\\webapps\\cleaning\\images\\"+fileName;
						 //如果头像已存在删除原来的头像(ROOT)
						       
							File localFile = new File(path);
							//服务器root/images图片复制到cleaning/images
							file.transferTo(localFile);
							boolean b=Copy(path,path2);
							Map<String, Object> param = new HashMap<String,Object>();
							param.put("lunbo","http://139.196.102.135/images/"+fileName);
							controllDao.insertLunbo(param);
						}
					}
				}
				
		}

	public void activityup(String text,HttpSession session,HttpServletRequest request,
				HttpServletResponse response) throws IllegalStateException, IOException, ParseException {
				
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
						request.getSession().getServletContext());
				if (multipartResolver.isMultipart(request)) {
					MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
					//获取所有文件
					Iterator<String> iter = multiRequest.getFileNames();
					Map<String,Object> param=new HashMap<String,Object>();
					param.put("text", text);
					int i=1;
					while (iter.hasNext()) {
						//获取当前文件
						MultipartFile file = multiRequest.getFile((String) iter.next());
						
						String fileName = file.getOriginalFilename();//储存地址
						if(fileName.substring(fileName.length()-4, fileName.length()).equals("peg")){
							if(i==1){
								fileName="activity"+System.currentTimeMillis()+fileName.substring(fileName.length()-5, fileName.length());
							}else{
								fileName="activityDetail"+System.currentTimeMillis()+fileName.substring(fileName.length()-5, fileName.length());
							}
						}else{
							if(i==1){
								fileName="activity"+System.currentTimeMillis()+fileName.substring(fileName.length()-4, fileName.length());
							}else{
								fileName="activityDetail"+System.currentTimeMillis()+fileName.substring(fileName.length()-4, fileName.length());
							}
						}
						if (fileName != null&&!fileName.equals("")) {//文件内容不为空
							String path1 = session.getServletContext().getRealPath("images")+File.separator;// 储存地址+文件名 
							String path = path1 +fileName;//创建文件
							String path2="C:\\Program Files\\Tomcat 7.0\\webapps\\cleaning\\images\\"+fileName;
							File localFile = new File(path);
							file.transferTo(localFile);
							Copy(path,path2);
							if(i==1){
								param.put("img1","http://139.196.102.135/cleaning/images/"+fileName);
							}else {
								param.put("img2","http://139.196.102.135/cleaning/images/"+fileName);
							}
							i=i+1;
						}
					}
					controllDao.insertActivity(param);
				}
				
		}
	
	public void addAunt(HttpSession session,HttpServletRequest request,
			HttpServletResponse responsename,String name,String age,String address,String idcard,String serviceType,String phoneNumber,String pwd,String honeLocation) throws IllegalStateException, IOException, ParseException {
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			if (multipartResolver.isMultipart(request)) {
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				//获取所有文件
				Iterator<String> iter = multiRequest.getFileNames();
				Map<String,Object> param=new HashMap<String,Object>();
				param.put("name", name);
				param.put("age", age+"岁");
				param.put("address", address);
				param.put("idcard", idcard);
				param.put("serviceType", serviceType);
				param.put("phoneNumber", phoneNumber);
				param.put("pwd", pwd);
				param.put("honeLocation", honeLocation);
				int i=1;
				while (iter.hasNext()) {
					//获取当前文件
					MultipartFile file = multiRequest.getFile((String) iter.next());
					
					String fileName = file.getOriginalFilename();//储存地址
					if(fileName.substring(fileName.length()-3, fileName.length()).equals("peg")){
						if(i==1){
							fileName=phoneNumber+System.currentTimeMillis()+fileName.substring(fileName.length()-5, fileName.length());
						}else if(i==2){
							fileName=phoneNumber+"zm"+System.currentTimeMillis()+fileName.substring(fileName.length()-5, fileName.length());
						}else{
							fileName=phoneNumber+"bm"+System.currentTimeMillis()+fileName.substring(fileName.length()-5, fileName.length());
						}
					}else{
						if(i==1){
							fileName=phoneNumber+System.currentTimeMillis()+fileName.substring(fileName.length()-4, fileName.length());
						}else if(i==2){
							fileName=phoneNumber+"zm"+System.currentTimeMillis()+fileName.substring(fileName.length()-4, fileName.length());
						}else{
							fileName=phoneNumber+"bm"+System.currentTimeMillis()+fileName.substring(fileName.length()-4, fileName.length());
						}
					}
					if (fileName != null&&!fileName.equals("")) {//文件内容不为空
						String path1 = session.getServletContext().getRealPath("images")+File.separator;// 储存地址+文件名 
						String path = path1 +fileName;//创建文件
						String path2="C:\\Program Files\\Tomcat 7.0\\webapps\\cleaning\\images\\"+fileName;
						File localFile = new File(path);
						//从ROOT复制到cleaning下
						file.transferTo(localFile);
						Copy(path,path2);
						if(i==1){
							param.put("head","http://139.196.102.135/cleaning/images/"+fileName);
						}else if(i==2){
							param.put("zm","http://139.196.102.135/cleaning/images/"+fileName);
						}else{
							param.put("bm","http://139.196.102.135/cleaning/images/"+fileName);
						}
						i=i+1;
					}
				}
				controllDao.insertAunt(param);
			}
			
	}

	

	
	/**
     * 微信统一下单接口
     * @param request
     * @param response
     */
    public Map<String,Object> wx(String orderNumber,String type,String redeemCode  ){
        Map<String, Object> resultMap = new HashMap<String, Object>();
         SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();
         Float price=0f;
         if(type.equals("日常保洁")||type.equals("日常保洁(一周一次)")||type.equals("日常保洁(一周多次)")||type.equals("日常保洁(两周一次)")){
        	 ROrder r=orderDao.findROrder(orderNumber);
        	 price=r.getRealPrice();
         }else if(type.equals("沙发护理")){
        	 SOrder r=orderDao.findSOrder(orderNumber);
       	 price=r.getRealPrice();
         }else if(type.equals("开荒保洁")){
        	 KOrder r=orderDao.findKOrder(orderNumber);
        	 price=r.getRealPrice();
         }else if(type.equals("家电清洗")){
        	 JOrder r=orderDao.findJOrder(orderNumber);
       	 price=r.getRealPrice();
         }else if(type.equals("地板护理")){
        	 DOrder r=orderDao.findDOrder(orderNumber);
        	 price=r.getRealPrice();
         }else if(type.equals("擦玻璃")){
        	 COrder r=orderDao.findCOrder(orderNumber);
        	 price=r.getRealPrice();
         }
         if(!redeemCode.equals("")&&redeemCode!=null){
     		Coupon cp=yuyueDao.findCouponByRedeemCode(redeemCode);
     		price=price-Float.valueOf(cp.getDiscountAmount());
         }
         price=price*100;
         parameters.put("appid", "wx50a88bb93c045066");  
         parameters.put("mch_id", "1464213402");  
         parameters.put("nonce_str",PayCommonUtil.CreateNoncestr()+","+redeemCode+","+type);  
         parameters.put("body", type);  
         parameters.put("out_trade_no", orderNumber+PayCommonUtil.CreateNoncestr()); //订单id
         parameters.put("fee_type", "CNY");  
         parameters.put("total_fee", (price+"").split("\\.")[0]);  
         parameters.put("spbill_create_ip","127.0.0.1");
         parameters.put("notify_url", "http://139.196.102.135/controll/yzwx"); 
         parameters.put("trade_type", "APP");  
        //设置签名
         String sign = PayCommonUtil.createSign("UTF-8",parameters);
         parameters.put("sign", sign);
       //封装请求参数结束
         String requestXML = PayCommonUtil.getRequestXml(parameters);  
        //调用统一下单接口
         String result = PayCommonUtil.httpsRequest(ConfigUtil.UNIFIED_ORDER_URL, "POST", requestXML);
         System.out.println("\n"+result);
         try {
         /**统一下单接口返回正常的prepay_id，再按签名规范重新生成签名后，将数据传输给APP。参与签名的字段名为appId，partnerId，prepayId，nonceStr，timeStamp，package。注意：package的值格式为Sign=WXPay**/
            Map<String, String> map = XMLUtil.doXMLParse(result);
            SortedMap<Object, Object> parameterMap2 = new TreeMap<Object, Object>();  
            parameterMap2.put("appid", ConfigUtil.APPID);  
            parameterMap2.put("partnerid", ConfigUtil.MCH_ID);  
            parameterMap2.put("prepayid", map.get("prepay_id"));  
            parameterMap2.put("package", "Sign=WXPay");  
            parameterMap2.put("noncestr", PayCommonUtil.CreateNoncestr());  

            //本来生成的时间戳是13位，但是ios必须是10位，所以截取了一下
            parameterMap2.put("timestamp", Long.parseLong(String.valueOf(System.currentTimeMillis()).toString().substring(0,10)));  
            String sign2 = PayCommonUtil.createSign("UTF-8",parameterMap2);
            parameterMap2.put("sign", sign2);  
            resultMap.put("code","200");
            resultMap.put("msg",parameterMap2);
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return resultMap;
    }
    
	public void yzwx(HttpServletRequest request,HttpServletResponse response) throws IOException, JDOMException, ParseException {
		  //读取参数  
        InputStream inputStream ;  
        StringBuffer sb = new StringBuffer();  
        inputStream = request.getInputStream();  
        String s ;  
        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));  
        while ((s = in.readLine()) != null){  
            sb.append(s);  
        }  
        in.close();  
        inputStream.close();  
        //解析xml成map  
        Map<String, String> m = new HashMap<String, String>();  
        m = XMLUtil.doXMLParse(sb.toString());  
        for(Object keyValue : m.keySet()){
            System.out.println(keyValue+"="+m.get(keyValue));
        }
        //过滤空 设置 TreeMap  
        SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();        
		Iterator it = m.keySet().iterator();  
        while (it.hasNext()) {  
            String parameter = (String) it.next();  
            String parameterValue = m.get(parameter);  

            String v = "";  
            if(null != parameterValue) {  
                v = parameterValue.trim();  
            }  
            packageParams.put(parameter, v);  
        }  

        //判断签名是否正确  
        String resXml = "";  
        if(PayCommonUtil.isTenpaySign("UTF-8", packageParams)) {
             if("SUCCESS".equals((String)packageParams.get("result_code"))){ 
                 // 这里是支付成功  
                 //////////执行自己的业务逻辑////////////////  
                 String mch_id = (String)packageParams.get("mch_id"); //商户号 
                 String openid = (String)packageParams.get("openid");  //用户标识
                 String out_trade_no = (String)packageParams.get("out_trade_no"); //商户订单号
                 String payType="微信"+out_trade_no;
                 out_trade_no=out_trade_no.substring(0, 14);
                 String total_fee = (String)packageParams.get("total_fee");  
                 String transaction_id = (String)packageParams.get("transaction_id"); //微信支付订单号
                 String noncestr = (String)packageParams.get("nonce_str"); //微信支付订单号

                 //查询订单 
                 String type=noncestr.split(",")[2];
                 String redeemCode=noncestr.split(",")[1];
                 Float price=0f;
                 if(type.equals("日常保洁")||type.equals("日常保洁(一周一次)")||type.equals("日常保洁(一周多次)")||type.equals("日常保洁(两周一次)")){
                	 ROrder r=orderDao.findROrder(out_trade_no);
                	 price=r.getRealPrice();
                 }else if(type.equals("家电清洗")){
                	 SOrder r=orderDao.findSOrder(out_trade_no);
                	 price=r.getRealPrice();
                 }else if(type.equals("开荒保洁")){
                	 KOrder r=orderDao.findKOrder(out_trade_no);
                	 price=r.getRealPrice();
                 }else if(type.equals("家电清洗")){
                	 JOrder r=orderDao.findJOrder(out_trade_no);
                	 price=r.getRealPrice();
                 }else if(type.equals("地板护理")){
                	 DOrder r=orderDao.findDOrder(out_trade_no);
                	 price=r.getRealPrice();
                 }else if(type.equals("擦玻璃")){
                	 COrder r=orderDao.findCOrder(out_trade_no);
                	 price=r.getRealPrice();
                 }
                 Map<String,Object> param=new HashMap<String,Object>(); 
         		param.put("orderNumber", out_trade_no);
         		param.put("redeemCode", redeemCode);
         		param.put("payType", payType);
         		param.put("type", "订单付款");
        		param.put("message", "类型:"+type+",订单编号:"+out_trade_no);
                 //有没有选择优惠券
                if(!redeemCode.equals("")&&redeemCode!=null){
                		Coupon cp=yuyueDao.findCouponByRedeemCode(redeemCode);
                		price=price-Float.valueOf(cp.getDiscountAmount());
                 }
                 String priceStr=(price*100+"").split("\\.")[0];
                 if(!ConfigUtil.MCH_ID.equals(mch_id)||new BigDecimal(total_fee).compareTo(new BigDecimal(priceStr)) != 0){
                 System.err.println("支付失败,错误信息：" + "参数错误"+new BigDecimal(total_fee)+"=="+new BigDecimal(priceStr));
                 resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"  
                                 + "<return_msg><![CDATA[参数错误]]></return_msg>" + "</xml> ";  
                 }else{
                	 if(type.equals("日常保洁")){
 						if(!redeemCode.equals("")){
 							Coupon cp=yuyueDao.findCouponByRedeemCode(redeemCode);
 							param.put("discountAmount", cp.getDiscountAmount());

 							yuyueDao.rbindCoupon(param);
 							couponDao.deleteCoupon(redeemCode);
 						}
 						ROrder r=orderDao.findROrder(out_trade_no);
 						if(r.getOrderTime()==null||r.getOrderTime().equals("")){
 							int start=0;
 							int end=0;
 							String circle=r.getCircle();
 							String[] days=circle.split(";")[0].split(",");
 							String[] slots=circle.split(";")[1].split(",");
 							for(int i=0;i<days.length;i++){
 								if(slots[i].substring(0, 1).equals("8")||slots[i].substring(0, 1).equals("9")){
 									start=Integer.valueOf(slots[i].substring(0, 1));
 								}else{
 									start=Integer.valueOf(slots[i].substring(0, 2));
 								}
 								end=Integer.valueOf(slots[i].substring(slots[i].length()-5, slots[i].length()-3));
 								yuyueService.updateYueMan(end-start+"",slots[i],days[i],1);
 							}
 						}else{
 							yuyueService.updateYueMan(r.getServiceTime()+"", r.getTimeSlot(),new SimpleDateFormat("yyyy年MM月dd日").format(new SimpleDateFormat("yyyy-MM-dd").parse(r.getOrderTime())),1);
 						}
 						
 						param.put("count", "+"+r.getRealPrice());
 						controllDao.createTongji(param);
 						yuyueDao.rzhifu(param);
 					}else if(type.equals("沙发护理")){
 						if(!redeemCode.equals("")){
 							Coupon cp=yuyueDao.findCouponByRedeemCode(redeemCode);
 							param.put("discountAmount", cp.getDiscountAmount());
 							yuyueDao.sbindCoupon(param);
 							couponDao.deleteCoupon(redeemCode);
 						}
 						SOrder r=orderDao.findSOrder(out_trade_no);
 						yuyueService.updateYueMan("4", r.getTimeSlot(),new SimpleDateFormat("yyyy年MM月dd日").format(new SimpleDateFormat("yyyy-MM-dd").parse(r.getOrderTime())),1);
 						param.put("count", "+"+r.getRealPrice());
 						controllDao.createTongji(param);
 						yuyueDao.szhifu(param);
 					}else if(type.equals("开荒保洁")){
 						if(!redeemCode.equals("")){
 							Coupon cp=yuyueDao.findCouponByRedeemCode(redeemCode);
 							param.put("discountAmount", cp.getDiscountAmount());
 							yuyueDao.kbindCoupon(param);
 							couponDao.deleteCoupon(redeemCode);
 						}
 						KOrder r=orderDao.findKOrder(out_trade_no);
 						yuyueService.updateYueMan("4", r.getTimeSlot(),new SimpleDateFormat("yyyy年MM月dd日").format(new SimpleDateFormat("yyyy-MM-dd").parse(r.getOrderTime())),1);
 						param.put("count", "+"+r.getRealPrice());
 						controllDao.createTongji(param);
 						yuyueDao.kzhifu(param);
 					}else if(type.equals("家电清洗")){
 						if(!redeemCode.equals("")){
 							Coupon cp=yuyueDao.findCouponByRedeemCode(redeemCode);
 							param.put("discountAmount", cp.getDiscountAmount());
 							yuyueDao.jbindCoupon(param);
 							couponDao.deleteCoupon(redeemCode);
 						}
 						JOrder r=orderDao.findJOrder(out_trade_no);
 						yuyueService.updateYueMan("4", r.getTimeSlot(),new SimpleDateFormat("yyyy年MM月dd日").format(new SimpleDateFormat("yyyy-MM-dd").parse(r.getOrderTime())),1);
 						param.put("count", "+"+r.getRealPrice());
 						controllDao.createTongji(param);
 						yuyueDao.jzhifu(param);
 					}else if(type.equals("地板护理")){
 						if(!redeemCode.equals("")){
 							Coupon cp=yuyueDao.findCouponByRedeemCode(redeemCode);
 							param.put("discountAmount", cp.getDiscountAmount());
 							yuyueDao.dbindCoupon(param);
 							couponDao.deleteCoupon(redeemCode);
 						}
 						DOrder r=orderDao.findDOrder(out_trade_no);
 						yuyueService.updateYueMan("4", r.getTimeSlot(),new SimpleDateFormat("yyyy年MM月dd日").format(new SimpleDateFormat("yyyy-MM-dd").parse(r.getOrderTime())),1);
 						param.put("count", "+"+r.getRealPrice());
 						controllDao.createTongji(param);
 						yuyueDao.dzhifu(param);
 					}else if(type.equals("擦玻璃")){
 						if(!redeemCode.equals("")){
 							Coupon cp=yuyueDao.findCouponByRedeemCode(redeemCode);
 							param.put("discountAmount", cp.getDiscountAmount());
 							yuyueDao.cbindCoupon(param);
 							couponDao.deleteCoupon(redeemCode);
 						}
 						COrder r=orderDao.findCOrder(out_trade_no);
 						yuyueService.updateYueMan("4", r.getTimeSlot(),new SimpleDateFormat("yyyy年MM月dd日").format(new SimpleDateFormat("yyyy-MM-dd").parse(r.getOrderTime())),1);
 						param.put("count", "+"+r.getRealPrice());
 						controllDao.createTongji(param);
 						yuyueDao.czhifu(param);
 					}
                    	 resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"  
                             + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";  
                          System.err.println("订单已处理");
                     
                 }
        }else {  
                 System.err.println("支付失败,错误信息：" + packageParams.get("err_code"));
                 resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"  
                         + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";  
             }  
        } else{  
            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"  
                    + "<return_msg><![CDATA[通知签名验证失败]]></return_msg>" + "</xml> "; 
            System.err.println("通知签名验证失败");
        }   
      //------------------------------  
        //处理业务完毕  
        //------------------------------  
        BufferedOutputStream out = new BufferedOutputStream(  
                response.getOutputStream());  
        out.write(resXml.getBytes());  
        out.flush();  
        out.close();  
    }
	

    
    
        public static boolean Copy(String start,String end)
        {
              try {  
                    //要拷贝的图片
                     BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File(start)));
                     //目标的地址
                     BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(end)));  
                     try {  
                         int val = -1;  
                         while((val=bis.read())!=-1){  
                            
                             bos.write(val);  
                         }  
                         bos.flush();  
                         bos.close();  
                         bis.close(); 
                         return true;
                    } catch (IOException e) {  
                    e.printStackTrace();              }  
                } catch (FileNotFoundException e) {  
                    e.printStackTrace();  
                } 
                return false;
        }

		public synchronized   Map<String, Object> wxVip(String vip,String phoneNumber ) {
			  Map<String, Object> resultMap = new HashMap<String, Object>();
		         SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();
		         Map<String,Object> param=new HashMap<String,Object>(); 
		         String number=new Date().getTime()+"";
		 		param.put("number",number );
		 		param.put("phoneNumber", phoneNumber);
		 		param.put("vip", vip);
		 		controllDao.createVip(param);
		 		String price="";
		 		if(vip.equals("1")){
		 			price="20000";
		 		}else if(vip.equals("2")){
		 			price="50000";
		 		}else if(vip.equals("3")){
		 			price="100000";
		 		}else if(vip.equals("4")){
		 			price="300000";
		 		}else if(vip.equals("5")){
		 			price="500000";
		 		}else if(vip.equals("6")){
		 			price="299900";
		 		}else if(vip.equals("7")){
		 			price="499900";
		 		}else if(vip.equals("8")){
		 			price="999900";
		 		}
		         parameters.put("appid", "wx50a88bb93c045066");  
		         parameters.put("mch_id", "1464213402");  
		         parameters.put("nonce_str",PayCommonUtil.CreateNoncestr()+","+vip+","+price+","+phoneNumber);  
		         parameters.put("body", "会员卡");  
		         parameters.put("out_trade_no", number); //订单id
		         parameters.put("fee_type", "CNY");  
		         parameters.put("total_fee", "1");  
/*		         parameters.put("total_fee", price);  
*/
		         parameters.put("spbill_create_ip","127.0.0.1");
		         parameters.put("notify_url", "http://139.196.102.135/controll/yzwxVip"); 
		         parameters.put("trade_type", "APP");  
		        //设置签名
		         String sign = PayCommonUtil.createSign("UTF-8",parameters);
		         parameters.put("sign", sign);
		       //封装请求参数结束
		         String requestXML = PayCommonUtil.getRequestXml(parameters);  
		        //调用统一下单接口
		         String result = PayCommonUtil.httpsRequest(ConfigUtil.UNIFIED_ORDER_URL, "POST", requestXML);
		         System.out.println("\n"+result);
		         try {
		         /**统一下单接口返回正常的prepay_id，再按签名规范重新生成签名后，将数据传输给APP。参与签名的字段名为appId，partnerId，prepayId，nonceStr，timeStamp，package。注意：package的值格式为Sign=WXPay**/
		            Map<String, String> map = XMLUtil.doXMLParse(result);
		            SortedMap<Object, Object> parameterMap2 = new TreeMap<Object, Object>();  
		            parameterMap2.put("appid", ConfigUtil.APPID);  
		            parameterMap2.put("partnerid", ConfigUtil.MCH_ID);  
		            parameterMap2.put("prepayid", map.get("prepay_id"));  
		            parameterMap2.put("package", "Sign=WXPay");  
		            //本来生成的时间戳是13位，但是ios必须是10位，所以截取了一下
		            parameterMap2.put("timestamp", Long.parseLong(String.valueOf(System.currentTimeMillis()).toString().substring(0,10)));  
		            parameterMap2.put("noncestr", PayCommonUtil.CreateNoncestr());  

		            String sign2 = PayCommonUtil.createSign("UTF-8",parameterMap2);
		            parameterMap2.put("sign", sign2);  
		            resultMap.put("code","200");
		            resultMap.put("msg",parameterMap2);
		        } catch (JDOMException e) {
		            e.printStackTrace();
		        } catch (IOException e) {
		            e.printStackTrace();
		        }
		        return resultMap;
		    }
		    

		public void yzwxVip(HttpServletRequest request, HttpServletResponse response) throws IOException, JDOMException, ParseException {
			  //读取参数  
	        InputStream inputStream ;  
	        StringBuffer sb = new StringBuffer();  
	        inputStream = request.getInputStream();  
	        String s ;  
	        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));  
	        while ((s = in.readLine()) != null){  
	            sb.append(s);  
	        }  
	        in.close();  
	        inputStream.close();  
	        //解析xml成map  
	        Map<String, String> m = new HashMap<String, String>();  
	        m = XMLUtil.doXMLParse(sb.toString());  
	        for(Object keyValue : m.keySet()){
	            System.out.println(keyValue+"="+m.get(keyValue));
	        }
	        //过滤空 设置 TreeMap  
	        SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();        
			Iterator it = m.keySet().iterator();  
	        while (it.hasNext()) {  
	            String parameter = (String) it.next();  
	            String parameterValue = m.get(parameter);  

	            String v = "";  
	            if(null != parameterValue) {  
	                v = parameterValue.trim();  
	            }  
	            packageParams.put(parameter, v);  
	        }  
	        //判断签名是否正确  
	        String resXml = "";  
	        if(PayCommonUtil.isTenpaySign("UTF-8", packageParams)) {
	             if("SUCCESS".equals((String)packageParams.get("result_code"))){ 
	                 // 这里是支付成功  
	                 //////////执行自己的业务逻辑////////////////  
	                 String mch_id = (String)packageParams.get("mch_id"); //商户号 
	                 String openid = (String)packageParams.get("openid");  //用户标识
	                 String out_trade_no = (String)packageParams.get("out_trade_no"); //商户订单号
	                 String total_fee = (String)packageParams.get("total_fee");  
	                 String transaction_id = (String)packageParams.get("transaction_id"); //微信支付订单号
	                 String noncestr = (String)packageParams.get("nonce_str"); //微信支付订单号

	                 //查询订单 
	                 String vip=noncestr.split(",")[1];
	                 String price=noncestr.split(",")[2];
	                 String phoneNumber=noncestr.split(",")[3];
	                 String uuid=out_trade_no;

	                 Map<String,Object> param=new HashMap<String,Object>(); 
	                 if(!ConfigUtil.MCH_ID.equals(mch_id)/*||new BigDecimal(total_fee).compareTo(new BigDecimal(price)) != 0*/){
	                 System.err.println("支付失败,错误信息：" + "参数错误"+new BigDecimal(total_fee)+"=="+new BigDecimal(price));
	                 resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"  
	                                 + "<return_msg><![CDATA[参数错误]]></return_msg>" + "</xml> ";  
	                 }else{
	                	 param.put("type", "购买会员卡");
	         			param.put("message", "用户:"+phoneNumber);
	         			param.put("count", "+"+price);
	         			toVip(vip,phoneNumber);
	         			controllDao.createTongji(param);
	         			controllDao.updateVip(uuid);
	                    	 resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"  
	                             + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";  
	                          System.err.println("订单已处理");
	                     
	                 }
	        }else {  
	                 System.err.println("支付失败,错误信息：" + packageParams.get("err_code"));
	                 resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"  
	                         + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";  
	             }  
	        } else{  
	            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"  
	                    + "<return_msg><![CDATA[通知签名验证失败]]></return_msg>" + "</xml> "; 
	            System.err.println("通知签名验证失败");
	        }   
	      //------------------------------  
	        //处理业务完毕  
	        //------------------------------  
	        BufferedOutputStream out = new BufferedOutputStream(  
	                response.getOutputStream());  
	        out.write(resXml.getBytes());  
	        out.flush();  
	        out.close();  
	    }

		public void delete(String path) {
			// TODO Auto-generated method stub

			 File targetFile = new File(path);
		        	targetFile.delete();
		
		}
		public Date addDay(Date day,int count) {
			Calendar calendar = Calendar.getInstance();
	        calendar.setTime(day);
	        calendar.add(Calendar.YEAR, count);
	        return calendar.getTime();
		}

		public Map<String, Object> version() {
	        Map<String, Object> map = new HashMap<String, Object>();  
			Version vs=controllDao.findVersion();
			map.put("version", vs);
			return map;
		}
		public Map<String, Object> versionAunt() {
	        Map<String, Object> map = new HashMap<String, Object>();  
			Version vs=controllDao.findVersionAunt();
			map.put("version", vs);
			return map;
		}

		public void addLocation(String location) {
			Location loca=controllDao.findLocation(location);
			if(loca==null){
				controllDao.addLocation(location);
			}
		}
		
		
}	
	
	
	
	
	
	

	
	 
	
	
	

